import React from "react";
import GoBack from "@/components/TheGoBack";
import { Form, Input, Select, Radio, Checkbox, Space, Button } from "antd";
import TheArea from "@/components/TheArea/editor";
import TheUpload from "@/components/TheUpload";
import "../style/style.less";
import { apiGetAdoptClassifyList, apiGetAdoptLabelList, apiGetAdoptEdit, apiGetAdoptDetails } from '@/request/adopt'
import _ from 'lodash'

const { TextArea } = Input;

class Editor extends React.Component {
  state = {
    addressProvince: "",
    addressProvinceId: '',
    addressCity: "",
    addressCityId: '',
    addressDistrict: "",
    addressDistrictId: '',
    tags: [],
    tagsValue: [],
    classifyList: [],
    btnLoading: false
  };
  async componentDidMount() {
    await this.getClassifyList()
    await this.getTagsList()
    await this.getData()
  }
  //获取详细数据
  getData = async () => {
    const { id } = this.props.match.params
    let res = await apiGetAdoptDetails({ petAdoptionId: id })
    if (res.data && res.code === 0) {
      let addressData = {
        province: res.data.addressProvinceId,
        provinceName: res.data.addressProvince,
        city: res.data.addressCityId,
        cityName: res.data.addressCity,
        area: res.data.addressDistrictId,
        areaName: res.data.addressDistrict
      }
      let petShowFile = res.data.petShowFile.split(',').map(v => {
        return {
          uid: v,
          name: 'image',
          url: v
        }
      })
      let petDetailsFiles = res.data.petDetailsFiles.split(',').map((v, i) => {
        return {
          uid: i,
          name: 'image',
          url: v,
          status: 'done'
        }
      })
      let tagsValue = res.data.petLabelIds.split(',')
      let petDescribe = res.data.petDescribe
      let adoptionGuidelines = res.data.adoptionGuidelines
      let adoptionDetailsId = res.data.adoptionDetailsId
      this.tagsChange(tagsValue)
      this.setState({ dataSource: res.data, addressData, petShowFileList: petShowFile, petDetailsFilesList: petDetailsFiles, petDescribe, adoptionGuidelines, adoptionDetailsId }, () => {
        this.formRef.setFieldsValue({ ...this.state.dataSource })
      })
    }
  }
  //获取类目
  getClassifyList = async () => {
    let res = await apiGetAdoptClassifyList({ status: '1' })
    if (res.data && res.code === 0) {
      let options = res.data
      let classifyList = options.map(v => {
        return {
          label: v.petAdoptionVarietyName,
          value: v.petAdoptionVarietyId
        }
      })
      this.setState({
        classifyList
      })
    }
  }
  //获取标签
  getTagsList = async () => {
    let res = await apiGetAdoptLabelList()
    if (res.data && res.code === 0) {
      let tags = res.data.map(v => {
        return {
          value: v.petLabelId,
          label: v.petLabelName
        }
      })
      this.setState({ tags })
    }
  }
  //设置省市区
  setAreaData = (data) => {
    const { provinceName, province, cityName, city, areaName, area } = data;
    this.formRef.setFieldsValue({ address: data });
    this.setState({
      addressProvince: provinceName,
      addressProvinceId: province,
      addressCity: cityName,
      addressCityId: city,
      addressDistrict: areaName,
      addressDistrictId: area,
    });
  };
  //标签选择
  tagsChange = (value) => {
    this.setState({ tagsValue: value }, () => {
      let { tags, tagsValue } = this.state;
      if (tagsValue.length === 5) {
        this.setState({
          tags: tags.map((v) => {
            return {
              ...v,
              disabled: !tagsValue.includes(v.value),
            };
          }),
        }, () => {
          this.formRef.setFieldsValue({ petLabelIds: this.state.tagsValue.join(',') })
        });
      } else {
        this.setState({
          tags: tags.map((v) => {
            return {
              ...v,
              disabled: false,
            };
          }),
        }, () => {
          this.formRef.setFieldsValue({ petLabelIds: this.state.tagsValue.join(',') })
        });
      }
    });
  };
  //图片上传回调
  getShowFileResult = (value) => {
    if (value && value.length) {
      let arr = value.map(v => {
        let data = ''
        if (v.response && v.response.code === 0) {
          data = v.response.data
        }
        return data
      })
      let petShowFile = arr.join(',')
      this.formRef.setFieldsValue({
        petShowFile
      })
    }
  };
  //图片上传回调
  getDetailsFileResult = value => {
    if (value && value.length) {
      let arr = value.map(v => {
        let data = ''
        if (v.response && v.response.code === 0) {
          data = v.response.data
        } else {
          data = v.url
        }
        return data
      })
      let petDetailsFiles = arr.join(',')
      this.formRef.setFieldsValue({
        petDetailsFiles
      })
    }
  }
  //form表单确定事件
  onFinish = async values => {
    this.setState({ btnLoading: true })
    const { id } = this.props.match.params
    if (values.address) {
      const { addressProvince, addressProvinceId, addressCity, addressCityId, addressDistrict,
        addressDistrictId } = this.state
      values.addressProvince = addressProvince
      values.addressProvinceId = addressProvinceId
      values.addressCity = addressCity
      values.addressCityId = addressCityId
      values.addressDistrict = addressDistrict
      values.addressDistrictId = addressDistrictId
    }
    delete (values.address)
    values.adoptionDetailsId = this.state.adoptionDetailsId
    let res = await apiGetAdoptEdit({ ...values, petAdoptionId: id })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '修改成功'
      })
      this.props.history.goBack()
    }
  }
  render() {
    const { tagsValue, tags, classifyList, btnLoading, petShowFileList, petDetailsFilesList, addressData, adoptionGuidelines, petDescribe } = this.state;
    return (
      <div className="p-layout-box adopt-editor-box">
        <div>
          <GoBack history={this.props.history} title="添加宠物领养" />
        </div>
        <div className="p-layout-content">
          <Form onFinish={this.onFinish} ref={ref => this.formRef = ref} labelCol={{ span: 3, offset: 1 }} labelAlign="left">
            <div className="title">基本信息</div>
            <Form.Item rules={[{ required: true }]} label="宠物类别" name="petAdoptionVarietyId">
              <Select options={classifyList} style={{ width: 200 }} />
            </Form.Item>
            <Form.Item rules={[{ required: true }]} label="宠物名称" name="petName">
              <Input style={{ width: 200 }} />
            </Form.Item>
            <Form.Item rules={[{ required: true }]} label="宠物性别" name="petSex">
              <Radio.Group value={'1'}>
                <Radio value={'1'}>雄</Radio>
                <Radio value={'2'}>雌</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item rules={[{ required: true }]} label="宠物年龄" name="petAge">
              <Input suffix="岁" style={{ width: 200 }} />
            </Form.Item>
            <Form.Item rules={[{ required: true }]} label="宠物所在地区" name="address">
              {
                !_.isEmpty(addressData) && <TheArea
                  addressData={addressData}
                  ref={(ref) => (this.addressRef = ref)}
                  setAreaData={this.setAreaData}
                />
              }
            </Form.Item>
            <Form.Item rules={[{ required: true }]} label="宠物标签" name="petLabelIds">
              <Checkbox.Group value={tagsValue} options={tags} onChange={this.tagsChange} />
              {`${tagsValue.length}/5`}
            </Form.Item>
            <Form.Item rules={[{ required: true }]} label="封面图" name="petShowFile">
              {
                !_.isEmpty(petShowFileList) && <TheUpload fileList={petShowFileList} maxSize={10} getFileResult={this.getShowFileResult} len={1} />
              }
            </Form.Item>
            <Form.Item rules={[{ required: true }]} label="宠物图集" name="petDetailsFiles">
              {
                !_.isEmpty(petDetailsFilesList) && <TheUpload fileList={petDetailsFilesList} maxSize={10} getFileResult={this.getDetailsFileResult} len={3} />
              }
            </Form.Item>
            <div className="title">宠物描述</div>
            <Form.Item rules={[{ required: true, message: '请填写宠物描述' }]} name="petDescribe">
              <div
                style={{
                  display: "flex",
                  justifyContent: "center",
                }}
              >
                {petDescribe && <TextArea
                  defaultValue={petDescribe}
                  style={{ width: 1000 }}
                  autoSize={{ minRows: 6, maxRows: 6 }}
                />}
              </div>
            </Form.Item>
            <div className="title">领养须知</div>
            <Form.Item rules={[{ required: true, message: '请填写领养须知' }]} name="adoptionGuidelines">
              <div
                style={{
                  display: "flex",
                  justifyContent: "center",
                }}
              >
                {adoptionGuidelines && <TextArea
                  defaultValue={adoptionGuidelines}
                  style={{ width: 1000 }}
                  autoSize={{ minRows: 6, maxRows: 6 }}
                />}
              </div>
            </Form.Item>
            <Form.Item>
              <div style={{ display: "flex", justifyContent: "center" }}>
                <Space>
                  <Button onClick={() => this.props.history.goBack()}>取消</Button>
                  <Button loading={btnLoading} htmlType="submit" type="primary">保存</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}

export default Editor;
